import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/http/common_net.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/pages/model/bean.dart';
import 'package:flutter_massage/pages/my/address/address_bean.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/sqlite/db_manager.dart';
import 'package:flutter_massage/values/constant.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:wechat_kit/wechat_kit.dart';

class ApiOrder extends CommonApi {
  ApiOrder.order(String key, String userId, String price, String cateId)
      : super('sign/?a=need', {
          'key': key,
          'user_id': userId,
          'cate_id': cateId,
          'price': price,
          'type': '2',
        });
}

class PlaceOrderLogic extends GetxController {
  PlaceOrderLogic({required this.projectId, required this.technicianId});

  final int projectId;
  final int technicianId;

  final TextEditingController textEditingController = TextEditingController();
  final FocusNode focusNode = FocusNode();

  late final StreamSubscription<BaseResp> _respSubs;

  AddressBean? addressBean;
  TechnicianBean? technicianBean;
  ProjectBean? projectBean;

  String time = '';
  String orderId = '';

  @override
  void onReady() {
    super.onReady();
    _respSubs = WechatKitPlatform.instance.respStream().listen(_listenResp);
    technicianBean = JsonService.getTechnicianById(technicianId);
    projectBean = JsonService.getProjectById(projectId);
    time = DateFormat('yyyy-MM-dd hh:mm').format(DateTime.now());
    update();
  }

  void _listenResp(BaseResp resp) {
    if (resp is PayResp) {
      if (resp.isSuccessful) {
        ///支付成功
        DbManager.saveOrder(
          orderId: orderId,
          time: time,
          desc: textEditingController.text,
          addressBean: addressBean!,
          technicianBean: technicianBean!,
          projectBean: projectBean!,
        );

        Loading.toast('下单成功');
        CommonRoute.close();
      }
    }
  }

  void save() async {
    if (Loading.predicate(() => addressBean == null, '请选择地址')) return;
    if (Loading.predicate(() => projectBean == null, '请选择项目')) return;
    if (Loading.predicate(() => technicianBean == null, '请选择技师')) return;
    if (Loading.predicate(() => time.empty, '请选择服务时间')) return;

    Loading.show();
    orderId = XydUserService.customId;
    String key = Storage().getString(StorageKey.userKey);
    dynamic json = await CommonNet.post(ApiOrder.order(
      key,
      technicianBean?.id?.toString() ?? '',
      (projectBean?.itemPrice ?? '').replaceAll('元', ''),
      // '0.01',
      projectBean?.itemId.toString() ?? '',
    ));
    Loading.dismiss();

    String appId = json['data']['sign']['appid'];
    String partnerId = json['data']['sign']['partnerid'];
    String prepayId = json['data']['sign']['prepayid'];
    String package = json['data']['sign']['package'];
    String nonceStr = json['data']['sign']['noncestr'];
    String timeStamp = json['data']['sign']['timestamp'];
    String link = json['data']['sign']['link'];
    String sign = json['data']['sign']['signPay'];

    await WechatKitPlatform.instance.registerApp(appId: appId, universalLink: link);

    WechatKitPlatform.instance.pay(
      appId: appId,
      partnerId: partnerId,
      prepayId: prepayId,
      package: package,
      nonceStr: nonceStr,
      timeStamp: timeStamp,
      sign: sign,
    );
  }
}
